﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Xwy.Practical.Models
{
    public class StudentRepository : IStudentRepository
    {
        public PraticalDbContext _context;

        public StudentRepository(PraticalDbContext context)
        {
            _context = context;
        }

        //插入数据
        public bool CreateStudent(Student student)
        {
            _context.Student.Add(student);
            return _context.SaveChanges() > 0;
        }

        //取全部记录
        public IEnumerable<Student> GetStudents()
        {
            return _context.Student.ToList();
        }

        //取某id记录
        public Student GetStudentByID(int id)
        {
            return _context.Student.SingleOrDefault(s => s.Id == id);
        }

        //根据id更新整条记录
        public bool UpdateStudent(Student student)
        {
            _context.Student.Update(student);
            return _context.SaveChanges() > 0;
        }

        //根据id更新名称
        public bool UpdateNameByID(int id, string name)
        {
            var state = false;
            var student = _context.Student.SingleOrDefault(s => s.Id == id);

            if (student != null)
            {
                student.Name = name;
                state = _context.SaveChanges() > 0;
            }

            return state;
        }

        //根据id删掉记录
        public bool DeleteStudentByID(int id)
        {
            var student = _context.Student.SingleOrDefault(s => s.Id == id);
            _context.Student.Remove(student);
            return _context.SaveChanges() > 0;
        }
    }
}
